package com.iuie.ns.datum.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iuie.ns.datum.vo.ZhichiSessionVO;
import com.iuie.ns.frame.utils.CSVUtils;
import com.iuie.ns.frame.utils.httpclients.ContentType;
import com.iuie.ns.frame.utils.httpclients.DefaultHttpResultHandler;
import com.iuie.ns.frame.utils.httpclients.HttpClientUtils;
import com.iuie.ns.frame.utils.httpclients.HttpParams;
import com.iuie.ns.frame.utils.httpclients.HttpRequestMethod;
import com.iuie.ns.system.service.code.ISysCodeInfoService;
import com.iuie.ns.system.vo.code.SysCodeInfoVO;

@Controller
@RequestMapping("test")
public class TestController {
	
	private static final Logger logger = LoggerFactory.getLogger(TestController.class);
	
	@Resource
	private ISysCodeInfoService codeInfoService;

	@RequestMapping("newYear")
	@ResponseBody	 
	public Map<String, Object> helloNewYear(String year, String partnerId, String token) {
		logger.info("year = {}, partnerId = {}, token = {}", new Object[]{year, partnerId, token});
		Map<String, Object> result = new HashMap<>();
		result.put("ret_code", 0);
		result.put("ret_message", "今年是 " + year + ", 新年快乐！");
		logger.info("正在调用接口---");
		return result;
	}
	
	@RequestMapping("getAllSessionData")
	@ResponseBody
	public Map<String, Object> getAllSessionData(ZhichiSessionVO session) {
		logger.info("sessions = {}", session);
		return null;
	}
	
	@RequestMapping("downloadCode")
	@ResponseBody
	public void downloadCSVCode(HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "form-data; name=\"attachment\";filename=\"code-list.csv\"");
		List<SysCodeInfoVO> lst = codeInfoService.findAll();
		CSVUtils.export(response.getOutputStream(), SysCodeInfoVO.class, lst, "yyyy-MM-dd");
	}
	
	@RequestMapping("pushCode")
	@ResponseBody
	public void pushCSVCode() throws IOException {
		List<SysCodeInfoVO> lst = codeInfoService.findAll();
		InputStream in = CSVUtils.exportInputStream(SysCodeInfoVO.class, lst, "yyyy-MM-dd");
		
		HttpParams params = HttpParams.newInstance()
				.url("http://localhost:8082/myboot/muti")
				.method(HttpRequestMethod.POST)
				.contentType(ContentType.MULTIPART_FORM_DATA)
				.addParam("file", in);
		String s = HttpClientUtils.send(params).handleResult(new DefaultHttpResultHandler());
		logger.info(s);
	}
}
